<template>
	<!-- 直播聊天室 -->
	<view class="live-detail">
		<view class="header">
			<view class="status-bar"></view>
			<view class="title flex-c">
				<view @click="fnGoBack()">
					<uni-icons type="arrowleft" size="24" color="#fff"></uni-icons>
				</view>
				<view class="flex-col-ac">
					<text>{{match_detail.match_type}}</text>
					<text class="time">{{match_detail.match_start_time}}</text>
				</view>
				<view></view>
			</view>
			<view class="vs-info flex-ac">
				<view class="team1 team flex-col-ac">
					<image :src="match_detail.home_logo"></image>
					<text>{{match_detail.home_name}}</text>
					<text>{{match_detail.home_position}}</text>
				</view>
				<view class="vs flex-col-ac">
					<text class="status">{{match_detail.status_name}}</text>
					<text class="grade">{{match_detail.score}}</text>
					<text class="grade1">{{match_detail.full_score}}</text>
				</view>
				<view class="team2 team flex-col-ac">
					<image :src="match_detail.away_logo"></image>
					<text>{{match_detail.away_name}}</text>
					<text>{{match_detail.away_position}}</text>
				</view>
			</view>
		</view>

		<view class="chatRoom">
			<image class="toBuy" src="../../static/live/imbought-color.png"></image>
			<view class="notice flex" v-if="match_detail.chat_room_status">
				<uni-icons type="info" size="20" color="#FF4420"></uni-icons>
				<text class="text">{{notice}}</text>
			</view>
			<scroll-view class="chatBox" scroll-y="true" :scroll-top="scrollTop" v-if="match_detail.chat_room_status">
				<view class="chatContent">
					<!-- <view class="chatItem">
						<text class="username">用户962933253：</text><text class="msg">尽职尽责你尽职尽责你尽职尽责你尽职尽责你尽职尽责你尽职尽责你尽职尽责你</text>
					</view> -->
					<view class="chatItem" v-for="(item,index) in messageList" :key="index">
						<text class="username">{{item.nickname}}:</text><text class="msg">{{item.content}}</text>
					</view>
				</view>
			</scroll-view>
			<view class="chatInput flex-bc" v-if="match_detail.chat_room_status">
				<view class="inputer flex">
					<text class="normal">常用</text>
					<input type="text" placeholder="看球不聊球等于没看球" style="font-size: 30rpx;" v-model="message" @blur="fnSendMessage()">
				</view>
				<uni-icons type="redo" size="24" color="#FF4420"></uni-icons>
			</view>
			<view class="none_wrap flex-col-ac" v-if="!match_detail.chat_room_status">
				<image src="/static/live/null-chat.png"></image>
				<text>聊天室暂未开放</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				match_id: '',
				token: uni.getStorageSync('token'),
				match_detail: {},
				isSocketOpen: false,
				socketlink: 'ws://caizhanbao.caimaomeng.com:8282',
				socketTask: null,
				notice: '聊天室禁止任何拉人及广告行为，违规者封号处理。',
				message: '',
				room_id: '',
				messageList: [],
				wrapHeight: '',
				chatH: '',
				scrollTop:0
			};
		},
		onLoad(option) { //页面传参
			console.log(option.match_id)
			this.match_id = option.match_id
			this.chatInit()
			var msg = {
				'type': 'room_info',
				'match_id': this.match_id,
				'token': this.token
			}
			console.log(msg)
			
			setInterval(()=>{
				this.clickRequest(msg)
			},10000)
			this.getChatRoomDetails()
		},
		mounted() {
			let that = this
			uni.getSystemInfo({
				success: function(res) { // res - 各种参数
					let info = uni.createSelectorQuery().select(".chatBox"); // 获取某个元素
					info.boundingClientRect(function(data) { //data - 各种参数
						console.log(data)
						that.wrapHeight = data.height;
					}).exec()
				}
			});
		},
		// 关闭websocket【必须在实例销毁之前关闭,否则会是underfined错误】
		beforeDestroy() {
			this.closeSocket();
		},
		methods: {
			getChatRoomDetails() {
				var that = this
				this.request({
					url: '/czb/football_live/getChatRoomDetails',
					method: 'POST',
					data: {
						'token': that.token,
						'match_id': that.match_id,
						'store_id': 1
			
					},
				}).then((ret) => {
					console.log(ret);
					if (ret.code == 0) {
						this.match_detail = ret.data
					}
					// if(ret.code == 1){
					// 	uni.showToast({
					// 		title: ret.message+'去登录',
					// 		icon: 'none'
					// 	})
					// 	setTimeout(function(){
					// 		uni.navigateTo({
					// 			url:'../login/login'
					// 		})
					// 	},1500)
					// }
				})
			},
			fnGoBack() {
				uni.navigateBack()
			},
			fnSendMessage() {
				var content = this.message
				if (!this.message) return uni.showToast({
					title: '请输入聊天内容',
					icon: 'none'
				})

				var msg = {
					'type': 'say',
					'match_id': this.match_id,
					'token': this.token,
					'content': content,
					'room_id': this.room_id
				}
				console.log(msg)
				this.clickRequest(msg)
			},
			chatInit() {

				var msg = {
					'type': 'login',
					'token': this.token,
					'match_id': this.match_id
				}
				console.log(msg)
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				this.socketTask = uni.connectSocket({
					// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
					url: this.socketlink,
					success(data) {
						console.log("websocket连接成功");
					},
				});

				// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");
					this.isSocketOpen = true;
					// 注：只有连接正常打开中 ，才能正常成功发送消息
					this.socketTask.send({
						data: JSON.stringify(msg),
						async success() {
							console.log("消息发送成功");
						},
					});
					// 注：只有连接正常打开中 ，才能正常收到消息
					this.socketTask.onMessage((res) => {
						console.log("收到服务器内容：" + res.data);
						var data = JSON.parse(res.data) //必须转换
						console.log(data)
						if (data.type == 'login') {
							this.room_id = data.data.room_id
							console.log(this.room_id)
						} else if (data.type == 'say') {
							console.log(data.data)
							this.messageList.push(data.data)
							this.message = '' //发送了消息就清空输入框
							console.log(this.messageList)
							this.fnSetScrollTop() //滚动滚动条 看到最新消息
						}else if(data.type == 'room_info'){
							this.match_detail = data.data
						}

					});
				})
				// 这里仅是事件监听【如果socket关闭了会执行】
				this.socketTask.onClose(() => {
					console.log("已经被关闭了")
				})
			},
			// 关闭websocket【离开这个页面的时候执行关闭】
			closeSocket() {
				this.socketTask.close({
					success(res) {
						this.isSocketOpen = false;
						console.log("关闭成功", res)
					},
					fail(err) {
						console.log("关闭失败", err)
					}
				})
			},
			clickRequest(msg) {
				if (this.isSocketOpen) {
					// websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
					this.socketTask.send({
						data: JSON.stringify(msg),
						async success() {
							console.log("消息发送成功");
						},
					});
				}
			},
			// 设置scrollTop值 保证用户能看到最新发送的消息
			fnSetScrollTop() {
				let that = this
				var space
				uni.getSystemInfo({
					success: function(res) { // res - 各种参数
						let info = uni.createSelectorQuery().select(".chatContent"); // 获取某个元素
						info.boundingClientRect(function(data) { //data - 各种参数
							console.log(data)
							that.chatH = data.height;
							space = (that.chatH - that.wrapHeight)
						}).exec()
					}
				});

				console.log(space)
				if (space > 0) {
					setTimeout(()=>{
						this.scrollTop = space + 20
					},100)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.live-detail {
		height: 100%;
	}

	.header {
		width: 100%;
		height: 440rpx;
		background: url(../../static/live/top-bg.png)no-repeat center/100%;

		.status-bar {
			height: var(--status-bar-height);
		}

		.title {
			font-size: 26rpx;
			color: #fff;
			height: 100rpx;

			view {
				flex: 1;
				padding: 0 20rpx;
			}

			.time {
				margin-top: 6rpx;
			}
		}

		.vs-info {
			flex: 1;
			margin-top: 30rpx;
			font-size: 30rpx;
			color: #fff;

			.team {
				image {
					width: 130rpx;
					height: 120rpx;
				}

			}

			.vs {
				.grade {
					font-size: 58rpx;
					margin: 20rpx 0 10rpx;
				}

				.grade1 {
					font-size: 28rpx;
				}

				.status {
					font-size: 24rpx;
				}
			}
		}
	}

	.chatRoom {
		width: 100%;
		height: calc(100% - 440rpx);
		background: #fff;
		position: relative;

		.notice {
			height: 80rpx;
			width: 100%;
			padding: 0 20rpx;
			box-sizing: border-box;
			background: #fff4f2;
			align-items: center;
			font-size: 26rpx;
			color: #FF4420;

			.text {
				margin-left: 20rpx;
				padding-left: 20rpx;
				border-left: .5rpx solid #ddd;
			}
		}

		.chatInput {
			// position: fixed;
			// bottom: 0;
			// left: 0;
			height: 120rpx;
			width: 100%;
			background: #fff;
			padding: 20rpx;
			box-sizing: border-box;

			.inputer {
				height: 100%;
				flex: 1;
				border-radius: 40rpx;
				background: #eee;
				font-size: 30rpx;
				align-items: center;
				margin-right: 20rpx;

				.normal {
					padding: 0 20rpx;
					border-right: 1rpx solid #ccc;
					color: #666;
				}

				input {
					padding: 0 20rpx;
					flex: 1;
				}
			}
		}

		.chatBox {
			width: 100%;
			height: calc(100% - 200rpx);
			background: #FAFDFF;
			padding: 0 20rpx;
			box-sizing: border-box;
			// overflow-y: scroll;
			// overflow-x: hidden;

			.chatContent {
				width: 100%;
				padding: 10rpx 0;

				.chatItem {
					font-size: 28rpx;
					color: #333;
					overflow: hidden;

					.username {
						color: #5CA1FC;
						margin-right: 10rpx;
						white-space: nowrap;
					}

					.msg {
						white-space: wrap;
					}
				}
			}
		}

		.toBuy {
			display: block;
			height: 130rpx;
			width: 130rpx;
			position: absolute;
			top: 120rpx;
			right: 20rpx;
		}

		.none_wrap {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			font-size: 26rpx;
			color: #999;

			image {
				width: 400rpx;
				height: 220rpx;
				margin-bottom: 32rpx;
			}
		}
	}
</style>
